<template>
	<view class="content">

		<!-- <view style="background-color: aqua; padding: 20rpx;" v-if="wyktp">
			<view class="">(测试比对)用户写完的画布图片</view>
			<image :src="wyktp" mode="widthFix"></image>
		</view> -->

		<view class="bottomBox">
			<view class="tip">请您在此手动签写自己的姓名，签写操作完毕请点击保存按钮 !</view>
			<!-- <button class="btn blue"
				style="margin-top: 20rpx; width: 195rpx; height: 100rpx; line-height: 100rpx; font-size: 35rpx; position: absolute; z-index: 9999; border-radius: 100rpx;"
				@click="verifySignature">验证</button> -->

			<button class="btn blue"
				style="margin-top: 20rpx; width: 195rpx; height: 100rpx; line-height: 100rpx; font-size: 35rpx; position: absolute; z-index: 9999; border-radius: 100rpx;"
				@click="save">保存</button>
			<view class="btn" style="margin-top: 150rpx;" @click="clear">清除</view>
			<view class="btn" @click="cancel">取消</view>
		</view>

		<view class="qianming">
			<view class="mingzi"
				:style="{'width': name.width, 'height': name.height, 'fontSize': name.size, 'marginTop': name.top}">
				{{user.chinaname}}
			</view>
			<!-- @touchend="end" -->
			<canvas class="canvas gui-box-shadow" disable-scroll="true" :style="{'width':width,'height':height}"
				canvas-id="designature" @touchstart="starts" @touchmove="moves"></canvas>
		</view>

		<gui-popup ref="guicx" :canCloseByShade="false">
			<view class="tanchuang3" style="padding: 45rpx;">
				<view style="color: red; padding-top: 10rpx;">注意: 一天只可提交三次，请勿频繁提交，请确认使用正楷书写后再提交</view>
				<view style="display: flex; justify-content: space-between; align-items: center; margin-top: 30rpx;">
					<button style="width: 145rpx; height: 75rpx; line-height: 75rpx;" @click="rewrite_cx">重写</button>
					<button type="primary" style="width: 145rpx; height: 75rpx; line-height: 75rpx;"
						@click="sumSignaturesDay">提交</button>
				</view>
			</view>
		</gui-popup>

		<gui-popup ref="guijzz" :canCloseByShade="false">
			<view class="tanchuang">
				加载中...
			</view>
		</gui-popup>

		<gui-popup ref="guiyzqm" :canCloseByShade="false">
			<view class="tanchuang">
				签名验证中...
			</view>
		</gui-popup>

		<gui-popup ref="guiqmcg" :canCloseByShade="false">
			<view class="tanchuang4">
				<text style="color: red;">签名成功！</text>签名成功后需要重新进入“会员证”页面查看新签名
			</view>
		</gui-popup>

		<gui-popup ref="guiyzjg" :canCloseByShade="false">
			<view class="tanchuang2">
				<view style="padding-top: 20rpx;" :class="verifySuccess == true ? 'gui-color-green' : 'gui-color-red'">
					{{verifySuccess ? '验证通过' : '验证失败'}}
				</view>
				<view style="margin-top: 20rpx;">
					<text>识别结果为: <br>{{recognizedText}}</text>
				</view>
				<button type="primary" style="margin-top: 20rpx; width: 230rpx; height: 75rpx; line-height: 75rpx;"
					@click="rewrite_yzjg">点击重写</button>
			</view>
		</gui-popup>

	</view>
</template>

<script>
	import grace from '@/Grace6/js/grace';
	export default {
		data() {
			return {
				// wyktp: false,
				user: [],
				dom: null,
				line: [],
				width: 0,
				height: 0,
				radius: 0,
				qm_img: null,
				// 用户名字样式
				name: {
					width: '1100rpx',
					height: '450rpx',
					size: '250rpx',
					top: '350rpx',
				},
				signatureOrNot: null,
				// 判断是否是会员证跳转过来的
				list: null,
				today: 0, // 当天是否还可提交签名(一天三次) 1为是，0为否

				verifyResult: false,
				verifySuccess: false,
				recognizedText: '',
			}
		},
		created() {
			uni.getSystemInfo({
				success: (res) => {
					this.width = res.windowWidth - 56 + 'px';
					this.height = res.windowHeight - 180 + 'px';
				}
			});
			this.dom = uni.createCanvasContext('designature', this);
			// uni.removeStorageSync('comparison');
			this.timeLimit();
		},
		onLoad(opt) {
			this.list = opt.list
			// console.log('idx: ', this.list);
			this.user = uni.getStorageSync("member");
			console.log(this.user, 'user');
			// this.user.chinaname = '柳江'
			// console.log(this.user.chinaname.length, '名字长度');
			if (this.user.chinaname.length === 2) {
				let mz = this.user.chinaname[0] + ' ' + this.user.chinaname[1]
				this.user.chinaname = mz
				this.name.size = '280rpx';
				this.name.top = '560rpx';
			} else if (this.user.chinaname.length === 4) {
				this.name.width = '1200rpx';
				this.name.height = '200rpx';
				this.name.size = '225rpx';
				this.name.top = '580rpx';
			}
		},
		methods: {
			open() {
				this.$refs.guiqmcg.open();
				setTimeout(() => {
					this.$refs.guiqmcg.close();
				}, 3000);
			},
			cancel() {
				uni.navigateBack()
			},
			open1() {
				this.$refs.guijzz.open();
			},
			close1() {
				this.$refs.guijzz.close();
			},
			distance(a, b) {
				let x = b.x - a.x;
				let y = b.y - a.y;
				return Math.sqrt(x * x + y * y);
			},
			starts(e) {
				// console.log(e)
				this.line.push({
					points: [{
						time: new Date().getTime(),
						x: e.touches[0].x,
						y: e.touches[0].y,
						dis: 0
					}]
				})
				let currentPoint = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
				this.currentPoint = currentPoint
				this.drawer(this.line[this.line.length - 1])
			},
			moves(e) {
				// console.log(e)
				let point = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
				this.lastPoint = this.currentPoint,
					this.currentPoint = point
				this.line[this.line.length - 1].points.push({
					time: new Date().getTime(),
					x: e.touches[0].x,
					y: e.touches[0].y,
					dis: this.distance(this.currentPoint, this.lastPoint)
				})
				this.signatureOrNot = 1
				// console.log('moves-signatureOrNot', this.signatureOrNot);
				this.drawer(this.line[this.line.length - 1])
			},
			drawer(item) {
				let x1, x2, y1, y2, len, radius, r, cx, cy, t = 0.5,
					x, y;
				var time = 0;
				if (item.points.length > 2) {
					let lines = item.points[item.points.length - 3];
					let line = item.points[item.points.length - 2];
					let end = item.points[item.points.length - 1];
					x = line.x;
					y = line.y;
					x1 = lines.x;
					y1 = lines.y;
					x2 = end.x;
					y2 = end.y;
					var dis = 0;
					time = (line.time - lines.time) + (end.time - line.time)
					dis = line.dis + lines.dis + end.dis;
					var dom = this.dom;
					var or = Math.min(time / dis * this.linePressure + this.lineMin, this.lineMax);
					cx = (x - (Math.pow(1 - t, 2) * x1) - Math.pow(t, 2) * x2) / (2 * t * (1 - t))
					cy = (y - (Math.pow(1 - t, 2) * y1) - Math.pow(t, 2) * y2) / (2 * t * (1 - t))
					dom.setLineCap('round')
					dom.beginPath();
					dom.setStrokeStyle('black')
					dom.setLineWidth(5)
					dom.moveTo(x1, y1);
					dom.quadraticCurveTo(cx, cy, x2, y2);

					dom.stroke();
					dom.draw(true)
				}
			},
			clear() {
				this.signatureOrNot = null
				this.dom.clearRect(0, 0, 1000, 1000)
				this.dom.draw()
			},
			rewrite_yzjg() {
				this.$refs.guiyzjg.close();
				this.clear();
			},
			rewrite_cx() {
				this.$refs.guicx.close();
				this.clear();
			},
			save() {
				if (this.signatureOrNot == null) {
					uni.showToast({
						title: '请先完成签名',
						icon: 'none',
						duration: 3000,
					});
					return;
				} else {
					// this.submitSignature();
					this.$refs.guicx.open();
				}
			},
			// 提交签名进行验证
			submitSignature() {
				this.$refs.guijzz.open();

				// 将画布内容转为图片
				uni.canvasToTempFilePath({
					canvasId: 'designature',
					fileType: 'jpg', // 使用JPG格式，更容易被OCR识别
					quality: 0.8, // 降低质量以减小文件大小
					// 设置更合适的尺寸，避免图片过大
					width: parseInt(this.width),
					height: parseInt(this.height),
					destWidth: 150, // 进一步降低分辨率
					destHeight: 150,
					success: res => {
						// this.wyktp = res.tempFilePath
						console.log('res.tempFilePath: ', res.tempFilePath);
						// 立即将图片转换为base64并保存
						// this.timeStorage();
						this.convertImageToBase64(res.tempFilePath);
					},
					fail: err => {
						console.error('画布转图片失败', err);
						uni.showToast({
							title: '签名保存失败',
							icon: 'none'
						});
					}
				}, this);
			},
			// 立即将图片转换为base64并保存
			convertImageToBase64(imagePath) {
				console.log(`立即转换图片为base64...`);
				try {
					// 使用plus.io获取base64数据
					// #ifdef APP-PLUS
					const path = plus.io.convertLocalFileSystemURL(imagePath); // 转换为绝对路径
					const fileReader = new plus.io.FileReader();

					fileReader.onloadend = (res) => {
						// 读取文件成功完成的回调函数
						if (res.target && res.target.result) {
							// 获取base64字符串，去掉前缀 "data:image/jpeg;base64,"
							const base64Data = res.target.result.split(',')[1];
							// const base64Data = res.target.result
							console.log(`图片转base64成功，长度: ${base64Data.length}`);
							// console.log('base64: ', base64Data);
							// 保存base64数据
							this.upload_qm(base64Data)
							// this.allSignatureBase64 = base64Data;
						} else {
							console.error(`图片转base64失败: 结果为空`);
							this.allSignatureBase64 = '';
						}
					};

					fileReader.onerror = (err) => {
						console.error(`图片转base64失败: ${JSON.stringify(err)}`);
						this.allSignatureBase64 = '';
					};

					// 读取文件为DataURL
					fileReader.readAsDataURL(path);
					// #endif

					// #ifndef APP-PLUS
					// 在非APP环境下使用uni.getFileSystemManager
					const fs = uni.getFileSystemManager();
					fs.readFile({
						filePath: imagePath,
						encoding: 'base64',
						success: res => {
							console.log(`图片转base64成功，长度: ${res.data.length}`);
							// 保存base64数据
							this.upload_qm(res.data)
							// this.allSignatureBase64 = res.data;
						},
						fail: err => {
							console.error(`读取图片文件失败: ${JSON.stringify(err)}`);
							// 设置为空字符串，后续处理时会使用模拟结果
							this.allSignatureBase64 = '';
						}
					});
					// #endif
				} catch (e) {
					console.error(`转换图片为base64异常: ${e.message}`);
					// 设置为空字符串，后续处理时会使用模拟结果
					this.allSignatureBase64 = '';
					// 尝试使用备用方法
					this.convertImageToBase64Fallback(imagePath);
				}
			},
			// 备用方法：使用canvas转换图片为base64
			convertImageToBase64Fallback(imagePath) {
				console.log(`使用备用方法转换图片为base64...`);

				try {
					// 创建临时canvas
					const tempCanvasId = 'tempCanvas';
					const ctx = uni.createCanvasContext(tempCanvasId, this);

					// 获取图片信息
					uni.getImageInfo({
						src: imagePath,
						success: imageInfo => {
							// 绘制图片到canvas
							ctx.drawImage(imagePath, 0, 0, imageInfo.width, imageInfo.height);
							ctx.draw(false, () => {
								// 导出canvas为base64
								uni.canvasToTempFilePath({
									canvasId: tempCanvasId,
									fileType: 'jpg',
									quality: 0.8,
									success: res => {
										// 再次尝试读取文件为base64
										const fs = uni.getFileSystemManager();
										fs.readFile({
											filePath: res.tempFilePath,
											encoding: 'base64',
											success: fileRes => {
												console.log(
													`备用方法：图片转base64成功，长度: ${fileRes.data.length}`
												);
												this.upload_qm(fileRes.data)
												// this.allSignatureBase64 = fileRes.data;
											},
											fail: err => {
												console.error(
													`备用方法：读取图片文件失败: ${JSON.stringify(err)}`
												);
												this.allSignatureBase64 = '';
											}
										});
									},
									fail: err => {
										console.error(
											`备用方法：canvas导出图片失败: ${JSON.stringify(err)}`
										);
										this.allSignatureBase64 = '';
									}
								}, this);
							});
						},
						fail: err => {
							console.error(`备用方法：获取图片信息失败: ${JSON.stringify(err)}`);
							this.allSignatureBase64 = '';
						}
					});
				} catch (e) {
					console.error(`备用方法：转换图片为base64异常: ${e.message}`);
					this.allSignatureBase64 = '';
				}
			},
			// 当天提交未超过三次，可再次提交
			sumSignaturesDay() {
				let self = this
				self.$refs.guicx.close();
				if (self.today == 1) {
					self.submitSignature();
				} else {
					uni.showToast({
						title: '已超过当天可提交次数，请隔天再试',
						icon: "none",
						duration: 3000,
					});
				}
			},
			// 验证签名讯飞接口
			verifySignature(base64Image) {
				console.log(base64Image);
				let self = this;
				this.$boya.NPost("/app/user_vip/update_sign", {
					"sign": base64Image,
					// "member_id": self.user.id
				}, function(res) {
					console.log("res", res);
					self.$refs.guiyzqm.close();
					if (res.code == 200) {
						self.$refs.guiqmcg.open();
						self.verifySuccess = true;
					} else {
						uni.showModal({
							content: res.msg
						})
					}

				}, function(err) {
					console.log("err", err);
					uni.showModal({
						content: err.msg
					})
					self.$refs.guiyzqm.close();
				})
				// let self = this
				// try {
				// 	let appId = '8026f074';
				// 	let apiKey = '67cc4947cc0f0d60ee26a24815cc567f';
				// 	let curTime = Math.round(new Date().getTime() / 1000);
				// 	let param = {
				// 		language: 'cn|en',
				// 		location: 'false',
				// 		imei: 'false',
				// 		osid: 'false',
				// 		ua: 'false',
				// 	};
				// 	let paramBase64 = btoa(JSON.stringify(param));
				// 	let checkSum = grace.md5(apiKey + curTime + paramBase64);

				// 	uni.request({
				// 		url: 'https://webapi.xfyun.cn/v1/service/v1/ocr/handwriting',
				// 		method: 'POST',
				// 		header: {
				// 			'X-Appid': appId,
				// 			'X-CurTime': curTime.toString(),
				// 			'X-Param': paramBase64,
				// 			'X-CheckSum': checkSum,
				// 			'Content-Type': 'application/x-www-form-urlencoded'
				// 		},
				// 		data: {
				// 			image: imagePath
				// 		},
				// 		success: (res) => {
				// 			if (res.statusCode === 200 && res.data && res.data.code === '0') {
				// 				console.log('res: ', res);
				// 				self.$refs.guiyzqm.close();
				// 				let textArr = []
				// 				let line = res.data.data.block[0].line
				// 				for (var i = 0; i < line.length; i++) {
				// 					textArr.push(line[i].word[0].content)
				// 				}
				// 				let text = textArr.join('');
				// 				let name = self.user.chinaname.replace(/\s+/g, '');
				// 				console.log('识别的文字: ', text);
				// 				console.log('用户姓名: ', name);
				// 				self.recognizedText = text || '无法识别';
				// 				// 判断识别文本是否与预期文本相似
				// 				// str.replace(/\s+/g, '')
				// 				if (text == name) {
				// 					self.open1();
				// 					self.verifySuccess = true;
				// 					self.upload_qm(imagePath);
				// 				} else {
				// 					self.$refs.guiyzjg.open();
				// 					self.verifySuccess = false;
				// 				}
				// 			} else {
				// 				console.log('err: ', res);
				// 				self.$refs.guiyzqm.close();
				// 				uni.showToast({
				// 					title: '签名识别失败，请重试',
				// 					icon: 'none'
				// 				});
				// 				return;
				// 			}
				// 		},
				// 		fail: (err) => {
				// 			console.error('请求失败:', err);
				// 			this.$refs.guiyzqm.close();
				// 			uni.showToast({
				// 				title: '签名识别失败，请重试',
				// 				icon: 'none'
				// 			});
				// 		}
				// 	});
				// } catch (err) {
				// 	console.error('OCR识别失败:', err);
				// 	uni.showToast({
				// 		title: '签名识别失败，请重试',
				// 		icon: 'none'
				// 	});
				// }
			},
			// 存储当前的比对签名时间
			timeStorage() {
				let self = this
				// 获取当前时间
				let comparison = uni.getStorageSync('comparison')
				let now = new Date();
				let year = now.getFullYear(); // 年
				let month = now.getMonth() + 1; // 月（注意月份是从0开始的，所以要加1）
				let date = now.getDate(); // 日
				let newTime = `${year}/${month}/${date}`;
				if (comparison) {
					comparison.time = newTime
					comparison.number++
					uni.setStorageSync('comparison', comparison);
					self.timeLimit();
				} else {
					comparison = {
						time: newTime,
						number: 1
					}
					uni.setStorageSync('comparison', comparison);
				}
			},
			// 用户一天内只可比对三次
			timeLimit() {
				let self = this
				let comparison = uni.getStorageSync('comparison')
				console.log('comparison: ', comparison);
				if (comparison) {
					let now = new Date();
					let year = now.getFullYear(); // 年
					let month = now.getMonth() + 1; // 月（注意月份是从0开始的，所以要加1）
					let date = now.getDate(); // 日
					let newTime = `${year}/${month}/${date}`;
					if (newTime == comparison.time) {
						if (comparison.number >= 3) {
							console.log('比对时间在当天，已没有提交次数');
							self.today = 0
						} else {
							console.log('比对时间在当天，但还有提交次数');
							self.today = 1
						}
					} else {
						self.today = 1
						console.log('比对时间非当天');
					}
				} else {
					self.today = 1
				}
				console.log('self.today: ', self.today);
			},
			// 提交签名
			upload_qm(baseQm) {
				let self = this;
				self.open1();
				this.$boya.NPost("/app/user_vip/update_sign", {
					sign: baseQm,
					// member_id: self.user.id // 用户id（可选）
				}, function(res) {
					console.log('res: ', res);
					self.timeStorage();
					if (res.code == 200) {
						self.close1();
						self.open();
						// self.timeLimit();
						setTimeout(function() {
							uni.navigateBack();
						}, 3000);
					} else {
						self.close1();
						uni.showToast({
							title: res.msg,
							icon: "none"
						});
					}
				}, function(err) {
					console.log('err: ', err);
					self.timeStorage();
					self.close1();
					self.clear();
					uni.showToast({
						title: err.msg,
						icon: "none",
						duration: 3000,
					});
				});
			},
		}
	}
</script>

<style lang="scss">
	.content {
		background-color: #fff;
		width: 100vw;
		height: 100vh;
		padding-bottom: 100rpx;

		.box {
			// height: 100vh;
			// background-color: #fff;
			border-radius: 20rpx;
			// padding: 12px 12px 100px;
			box-shadow: 0 6rpx 42rpx rgba(0, 0, 0, 0.05);
		}

		.mingzi {
			// 类似手写风格的字体
			font-family: cursive;
			color: gainsboro;
			line-height: 750rpx;
			transform: rotate(90deg);
			position: absolute;
			z-index: 99;
		}

		.canvas {
			// rgba(255, 255, 255, 0.5) #E6E6E6;
			// background-color: rgba(255, 255, 255, 0.5);
			// background: url('../../static/zhongqiu/bj2.jpg') 100% 100% / 100% 100%;
			// transform: rotate(-90deg);
			position: relative;
			z-index: 999;
		}

		.bottomBox {
			// flex-direction: column;
			// justify-content: center;
			width: 200rpx;
			height: 500rpx;
			// padding: 10px;
			// background-color: #007AFF;
			// position: fixed;
			// top: -150rpx;
			transform: rotate(90deg);
			margin-top: -100rpx;
			margin-left: 300rpx;

			.tip {
				font-size: 24rpx;
				color: #FF6F77;
			}

			.btn {
				width: 100%;
				height: 80rpx;
				background: #F5F5F5;
				border-radius: 40rpx;
				margin-top: 20rpx;
				text-align: center;
				line-height: 80rpx;
				color: #333333;
				font-size: 13px;

				&.blue {
					background: #284CF4;
					color: #fff;
				}
			}
		}
	}

	.qianming {
		margin-top: -100rpx;
		margin-left: 50rpx;
	}

	.tanchuang {
		transform: rotate(90deg);
		width: 260rpx;
		height: 300rpx;
		color: white;
		font-size: 45rpx;
		font-weight: bold;
		text-align: center;
		line-height: 200rpx;
		// background-color: rgba(0, 0, 0, 0.3);
		border-radius: 20rpx;
		margin: 0 auto;
	}

	.tanchuang2 {
		transform: rotate(90deg);
		width: 270rpx;
		height: 300rpx;
		font-size: 40rpx;
		font-weight: bold;
		text-align: center;
		background-color: white;
		border-radius: 20rpx;
		margin: 0 auto;
	}

	.tanchuang3 {
		transform: rotate(90deg);
		width: 280rpx;
		height: 250rpx;
		font-size: 35rpx;
		font-weight: bold;
		text-align: center;
		background-color: white;
		border-radius: 20px;
		margin: 0 auto;
	}

	.tanchuang4 {
		transform: rotate(90deg);
		width: 280rpx;
		height: 260rpx;
		font-size: 40rpx;
		font-weight: bold;
		text-align: center;
		background-color: white;
		border-radius: 20rpx;
		margin: 0 auto;
		padding: 55rpx 20rpx 0 20rpx;
	}
</style>